import { DateService } from './../../date/src/date.service'
import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Sms } from './sms.entity'
import { Repository } from 'typeorm'
import sms = require('ali-sms')

@Injectable()
export class SmsService {
  constructor(@InjectRepository(Sms) public sms: Repository<Sms>, private date: DateService) {}

  async getSmsList() {
    return await this.sms.find({
      order: { createAt: 'DESC' }
    })
  }

  async sendSmsCode(mobile: string) {
    const code = Math.floor(Math.random() * 1000)
    const sms = new Sms()
    sms.code = code + ''
    sms.mobile = mobile
    sms.status = 1
    await this.sms.save(sms)
    return sms
  }

  async smsTodayTotal() {
    const smsBuilder = this.sms.createQueryBuilder()
    return await smsBuilder
      .where('createAt > :createAt', { createAt: this.date.dayDate })
      .getCount()
  }

  async smsMonthTotal() {
    const smsBuilder = this.sms.createQueryBuilder()
    return await smsBuilder
      .where('createAt > :createAt', { createAt: this.date.monthDate })
      .getCount()
  }

  async smsMonthSuccessTotal() {
    const smsBuilder = this.sms.createQueryBuilder()
    return await smsBuilder
      .where('status=:status', { status: 1 })
      .where('createAt > :createAt', { createAt: this.date.monthDate })
      .getCount()
  }

  async smsTodaySuccessTotal() {
    const smsBuilder = this.sms.createQueryBuilder()
    return await smsBuilder
      .where('status = :status', { status: 1 })
      .where('createAt > :createAt', { createAt: this.date.dayDate })
      .getCount()
  }
}
